// Promise 封装 wx.request
const app = getApp()
const METHOD = {
    GET: 'GET',
    POST: 'POST'
}

Promise.prototype.finally = function (callback) {
    const P = this.constructor
    return this.then(
        value => P.resolve(callback()).then(() => value),
        reason => P.resolve(callback()).then(() => { throw reason })
    )
}

function isAbsoluteURL(url) {
    return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url)
}

function combineURLs(url) {
    return app.d.severUrl + url
}

function request(url, data, method, header) {
    const promise = new Promise((resolve, reject) => {
        const token = wx.getStorageSync("token")

        wx.request({
            url: isAbsoluteURL(url) ? url : combineURLs(url),
            data: token ? {  token, ...data } : data,
            method,
            header,
            success: res => {
                if (res.statusCode === 200) {
                    if (res.data.code === 0) {
                        resolve(res.data)
                    } else {
                        reject(res.data)
                    }
                } else {
                    switch (res.statusCode) {
                        case 400:
                            reject({ msg: '请求错误' })
                            break
                        
                        case 404:
                            reject({ msg: '接口不存在' })
                            break

                        case 500:
                            reject({ msg: '服务器错误' })
                            break

                        default:
                    }
                }
            },
            fail: error => {
                switch (error.errMsg) {
                    case 'request:fail timeout':
                        reject({ msg: '请求超时' })
                        break

                    default:
                        reject({ msg: '网络错误' })
                        break
                }
            }
        })
    })

    return promise
}

function get(url, data) {
    const header = {
        'content-type': 'application/json'
    }
    return request(url, data, METHOD.GET, header)
}

function post(url, data) {
    const header = { 
        'content-type': 'application/x-www-form-urlencoded'
    }
    return request(url, data, METHOD.POST, header)
}

module.exports = {
    get,
    post
}
